﻿using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
    public class Timeout : DemoBase
    {
        public override string DemoName => "Polly-Timeout Demo";

        public override void RunDemo()
        {
            base.Init();

            int runTimes = 10;
            int timeout = 2;

            var policy = Policy.Timeout(timeout, Polly.Timeout.TimeoutStrategy.Pessimistic);

            for (int i = 1; i <= runTimes; i++)
            {
                try
                {
                    PrintInfo($"第{i}次执行");
                    policy.Execute(RequestFromWeb);
                }
                catch (Exception e)
                {
                    PrintError($"异常：{e.GetType().Name},{e.Message}");
                }
            }
        }

        private void RequestFromWeb()
        {
            if (new Random().Next(10) < 5)
            {
                Thread.Sleep(3_000);
            }
            else
            {
                PrintSuccessLog("网络请求响应完毕");
            }
        }
    }
}
